package com.weijing.pretty_app.util

import android.content.Context
import android.util.Log
import app.akexorcist.bluetotohspp.library.BluetoothSPP
import app.akexorcist.bluetotohspp.library.BluetoothState
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R

object BluetoothSPPManager {

    private var btSPP: BluetoothSPP? = null
    private val listeners = mutableListOf<(data: ByteArray) -> Unit>()
    private var isConnected = false

    fun init(context: Context) {
        if (btSPP == null) {
            btSPP = BluetoothSPP(context.applicationContext)
            btSPP?.setupService()    // **必须调用这一步初始化服务**
            btSPP?.startService(BluetoothState.DEVICE_OTHER) // 启动蓝牙服务
            btSPP?.setBluetoothConnectionListener(object :
                BluetoothSPP.BluetoothConnectionListener {
                override fun onDeviceConnected(name: String?, address: String?) {
                    isConnected = true
                    Log.i("BluetoothSPPManager", "Connected to $name ($address)")
                    ToastUtils.show(context.getString(R.string.Bluetooth_Connected))
                    LiveEventBus.get<String>(KeyUtil.NOTICE_DEVICE_ID).post(address)
                    LiveEventBus.get<String>(KeyUtil.CLOSE_BLUETOOTH_ACTIVITY).post(address)
                }

                override fun onDeviceDisconnected() {
                    isConnected = false
                    Log.i("BluetoothSPPManager", "Disconnected")
                }

                override fun onDeviceConnectionFailed() {
                    isConnected = false
                    ToastUtils.show(context.getString(R.string.Bluetooth_Connected_failed))
                    Log.i("BluetoothSPPManager", "Connection failed")
                }
            })

            btSPP?.setOnDataReceivedListener { data, _ ->
                // 收到数据，通知所有注册的监听者
                listeners.forEach { it.invoke(data) }
            }
        }
    }

    /**
     * 连接设备，address是蓝牙设备MAC地址
     */
    fun connect(address: String) {
        if (btSPP == null) {
            Log.e("BluetoothSPPManager", "BluetoothSPP not initialized!")
            return
        }
        if (isConnected) {
            Log.i("BluetoothSPPManager", "Already connected")
            return
        }
        btSPP?.connect(address)
    }

    fun disconnect() {
        btSPP?.disconnect()
        isConnected = false
    }

    fun send(data: ByteArray) {
        if (isConnected) {
            btSPP?.send(data, false)
        } else {
            Log.w("BluetoothSPPManager", "Send failed: not connected")
        }
    }

    /**
     * 注册数据接收回调，多个回调都可以接收
     */
    fun addDataReceivedListener(listener: (data: ByteArray) -> Unit) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    /**
     * 移除数据接收回调
     */
    fun removeDataReceivedListener(listener: (data: ByteArray) -> Unit) {
        listeners.remove(listener)
    }

    fun isConnected(): Boolean = isConnected

    fun getBluetoothSPP(): BluetoothSPP? = btSPP
}